//
//  String+Extensons.swift
//  MattressTool
//
//  Created by Coder Yang on 2023/11/20.
//

import Foundation

extension String {
    /// 字符串转[UInt8]
    /// - Returns: Ascii值
    func toAscii() -> [UInt8] {
        var bytes: [UInt8] = []
        for scalars in self.unicodeScalars {
            bytes.append(UInt8(scalars.value))
        }
        return bytes
    }
    
    /// 从索引开始截取
    /// - Parameter from: 开始索引
    /// - Returns: 字串
    func substring(from: Int) -> String {
        let index = index(from: from)
        return String(self[index...])
    }
    
    /// 截取到索引位置
    /// - Parameter to: 结束索引
    /// - Returns: 子串
    func substring(to: Int) -> String {
        let index = index(from: to)
        return String(self[..<index])
    }
    
    /// 范围截取
    /// - Parameter range: 范围
    /// - Returns: 子串
    func substring(with range: Range<Int>) -> String {
        let startIndex = index(from: range.lowerBound)
        let endIndex = index(from: range.upperBound)
        return String(self[startIndex..<endIndex])
    }
    
    /// 索引
    private func index(from: Int) -> Index {
        return self.index(startIndex, offsetBy: from)
    }
    
    /// 切割字符串
    /// - Parameters:
    ///   - stride: 步长
    ///   - separator: 分割符
    /// - Returns: 新串
    func slice(every stride: Int = 2, with separator: Character = ":") -> String {
        String(enumerated().map { $0 > 0 && $0 % stride == 0 ? [separator, $1] : [$1] }.joined())
    }
}
